package com.lrkj.back.controller;

import java.io.IOException;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.lrkj.back.Const;
import com.lrkj.back.StartUpOnLoadData;
import com.lrkj.back.entity.TbDepartment;
import com.lrkj.back.entity.TbDict;
import com.lrkj.back.entity.ZsPackageImformation;
import com.lrkj.back.service.TbDepartmentService;
import com.lrkj.back.service.TbPackageMubanService;
import com.lrkj.back.service.TbProductService;
import com.lrkj.back.entity.TbProduct;
import com.lrkj.back.service.ZsPackageImformationService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.com.cbons.mamisay.parent.exception.BusinessException;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.github.pagehelper.PageInfo;
@Controller
@RequestMapping("/product")
public class TbProductController extends BaseController{
	
	public class ProductNum implements Serializable{
		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;
		
		String name;
		
		Integer num;
		
		String id;

		ProductNum(){
			
		}
		ProductNum(String name,Integer num){
			this.name = name;
			this.num = num;
		}
		public void setName(String name){
			this.name = name;
		}
		@Override
		public String toString() {
			return "ProductNum [name=" + name + ", num=" + num + ", id=" + id
					+ "]";
		}
		public String getName() {
			return name;
		}
		public Integer getNum() {
			return num;
		}

		public void setNum(Integer num) {
			this.num = num;
		}

		public String getId() {
			return id;
		}

		public void setId(String id) {
			this.id = id;
		}
	}
	
	@Autowired
	private TbProductService chanpinservice;
	@Autowired
	private TbProductService tbProductService;
	@Autowired
	private ZsPackageImformationService zsPackService;
	@Autowired
	private TbPackageMubanService tbPackMubanService;

	@Autowired
	private TbDepartmentService tbDepartmentService;

	//配置--器械信息   （点击查询）
	@RequestMapping(value="/productList.do")
	public ModelAndView productList(String searchTxt,String dictId,String protypeId,HttpServletRequest request,HttpServletResponse response)throws BusinessException{
		Integer pageNo = request.getParameter("pageIndex")==null? 1 :Integer.valueOf(request.getParameter("pageIndex"));
		Map<String,Object> map =new HashMap<>();
		if(StringUtils.isNotBlank(searchTxt)){
			//TODO 此处查询功能需完善
			map.put("productId", searchTxt.trim());
			map.put("productName", searchTxt.trim());
			map.put("productCode", searchTxt.trim());
		}
		if(StringUtils.isNotBlank(dictId)&&!"0".equals(dictId)){
			map.put("protypeRefid2",Integer.valueOf(dictId));
		}
		if(StringUtils.isNotBlank(protypeId)&&!"0".equals(protypeId)){
			map.put("protypeId",Integer.valueOf(protypeId));
		}
		map.put("pageNo", pageNo);
		map.put("pageSize", Const.PAGE_SIZE);
		List<TbDict> productTypeList = StartUpOnLoadData.dataListMap.get(StartUpOnLoadData.WPFL);
		List<TbDict> prodTypeList =  StartUpOnLoadData.dataListMap.get(StartUpOnLoadData.QXFL);
		Map<Integer,Object> productTypeMap = new HashMap<>();
		Map<Integer,Object> prodTypeMap = new HashMap<>();

		for(TbDict tbDict:productTypeList){
			productTypeMap.put(tbDict.getDictId(),tbDict.getDictName());
		}
		for(TbDict tbDict:prodTypeList){
			prodTypeMap.put(tbDict.getDictId(),tbDict.getDictName());
		}
		PageInfo<TbProduct> page = chanpinservice.findAllProductList(map);
		request.setAttribute("productTypeList",productTypeList);
		request.setAttribute("prodTypeList",prodTypeList);
		request.setAttribute("prodTypeMap",prodTypeMap);
		request.setAttribute("productTypeMap", productTypeMap);
		request.setAttribute("productList", page.getList());
		request.setAttribute("dictId",dictId);
		request.setAttribute("protypeId",protypeId);
		request.setAttribute("searchTxt", searchTxt==null?"":searchTxt);
		request.setAttribute("total", page.getPages());
		return new ModelAndView("/peizhi/qixiexinxi/qixie_list");
	}
		//点添加按纽用到的方法
	@RequestMapping("/productEdit.do")
	public ModelAndView productEdit(Integer id, HttpServletRequest request,
			HttpServletResponse response)throws BusinessException{
		TbProduct product = (id == null) ? new TbProduct() : chanpinservice.selectByPrimaryKey(id);
		if(id==null){
			SimpleDateFormat sdf= new SimpleDateFormat("yyyyMMddHHmmssSSS");
			String no = sdf.format(new Date());
			product.setProductNo(no);
		}
		request.setAttribute("product", product);
		//查找器械分类
		Map<String,Object> map = new HashMap<>();
		List<TbDepartment> tbDepartments =  tbDepartmentService.findDepartment(map);
		List<TbDict> proTypelist = StartUpOnLoadData.dataListMap.get(StartUpOnLoadData.QXFL);
		//查找物品分类
		List<TbDict> productTypeList = StartUpOnLoadData.dataListMap.get(StartUpOnLoadData.WPFL);
		request.setAttribute("proTypelist", proTypelist);
		request.setAttribute("productTypeList",productTypeList);
		request.setAttribute("tbDepartments",tbDepartments);
		return new ModelAndView("/peizhi/qixiexinxi/qixie_edit");
	}
	
	@RequestMapping(value="/productSave.do",method=RequestMethod.POST)
	@ResponseBody
	public Map<Object,Object> productSave(TbProduct product ,HttpServletRequest request,
			HttpServletResponse response)throws BusinessException{
		Map<Object, Object> rtnMap = new HashMap<>();
		try {

			if(product.getProductId() ==null ){
				product.setProductCreatetime(new Date());
				chanpinservice.insert(product);
			}else{
				chanpinservice.updateByPrimaryKey(product);
				product = chanpinservice.selectByPrimaryKey(product.getProductId());
			}
			rtnMap.put("status", "true");
			rtnMap.put("product",product);
			rtnMap.put("msg", "编辑成功");
		} catch (Exception e) {
			rtnMap.put("status", "false");
			rtnMap.put("msg", "编辑失败");
			e.printStackTrace();
		}
		return rtnMap;
	}
	
	@RequestMapping(value="/productDelete.do")
	@ResponseBody
	public Map<Object,Object> productDelete(HttpServletRequest request,HttpServletResponse response)throws BusinessException{
		Map<Object, Object> rtnMap = new HashMap<Object,Object>();
		try {
			String ids = request.getParameter("id");
			String[] arraId = ids.split(",");
			for(String tid : arraId){
				chanpinservice.deleteByPrimaryKey(Integer.valueOf(tid));
			}
			rtnMap.put("status", "true");
			rtnMap.put("msg", "删除成功");
		} catch (Exception e) {
			rtnMap.put("status", "false");
			rtnMap.put("msg", "删除失败");
			e.printStackTrace();
		}
		return rtnMap;
	}
	
	//FIXME
	@RequestMapping("/findQixieList.do")
	@ResponseBody
	public Map<Object,Object> findQixieList(String id,String name,HttpServletRequest request,HttpServletResponse response)throws BusinessException{
		Map<Object, Object> rtnMap = new HashMap<>();
		try {
			Integer sid = Integer.valueOf(id);
			Map<String,Object> map =new HashMap<>();
			map.put("packageId", sid);
			List<TbProduct> products = tbProductService.findAllProducts(map);
			request.setAttribute("tbproductList",products);
			request.setAttribute("packageId", sid);
			rtnMap.put("qixie",products);
			rtnMap.put("status","true");
			rtnMap.put("msg", "查询成功");
		} catch (Exception e) {
			rtnMap.put("status","false");
			rtnMap.put("msg", "查询失敗");
			e.printStackTrace();
		}
		return rtnMap;
	}
	
	@RequestMapping("/mazui.do")
	@ResponseBody
	public Map<Object,Object> mazui(String appid,String baoArray,HttpServletRequest request,HttpServletResponse response)throws BusinessException, UnsupportedEncodingException, IOException{
		String [] baoArr = baoArray.split(",");
		Map<String,Object> map = new HashMap<>();
		Map<Object,Object> rtnMap = new HashMap<>();
		int baolength = baoArr.length;
		map.put("packageTiaomaArr", baoArr);
		if(baoArr.length!=0){
			List<ZsPackageImformation> zsPackList =  zsPackService.findAll(map);
			if(zsPackList.size()==baolength){
				Map<String,ProductNum> productNumMap =new HashMap<>();
				for(int i =0;i<zsPackList.size();i++){
					ZsPackageImformation zsPack = zsPackList.get(i);
					int baoId = zsPack.getPackageId();
					map.put("packageId", baoId);
					List<TbProduct> products = tbProductService.findQixieByPackage(map);
					for(int j =0;j<products.size();j++){
						TbProduct tbProduct = new TbProduct();
						tbProduct = products.get(j);
						Integer productNum = tbProduct.getNum();
						String productName = tbProduct.getProductName();
						String productId = String.valueOf(tbProduct.getProductId());
						ProductNum productnumShiti = null;
						if(!productNumMap.containsKey(productId)){
							productnumShiti = new ProductNum(productName,productNum);
							productNumMap.put(productId, productnumShiti);
						}else{
							productnumShiti = productNumMap.get(productId);
							productnumShiti.setNum(productnumShiti.num+productNum);
							productNumMap.put(productId,productnumShiti);
						}
						
					}
					List<ProductNum> productList = new ArrayList<ProductNum>();
					ProductNum product = null;
					for (Map.Entry<String, ProductNum> entry : productNumMap.entrySet()) {
						product = new ProductNum();
						String key = entry.getKey();
			            product = entry.getValue();
			            product.setId(key);
			            productList.add(product);
			        }  
					rtnMap.put("productList", productList);
					rtnMap.put("status", "true");
					rtnMap.put("msg", "编辑成功");
				}
			}else{
				rtnMap.put("status", "false");
				rtnMap.put("msg", "有不匹配的包，请重新录入条码");
			}
		}
		return rtnMap;
		
	}
	
}
